package org.darkforest.service.impl;

import org.apache.commons.lang.StringUtils;
import org.darkforest.common.services.SimpleRedisService;
import org.darkforest.model.Token;
import org.darkforest.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 令牌服务实现接口
 *
 * @auth bingo
 * @create 2017-09-25-17:03
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private SimpleRedisService simpleRedisService;

    /**
     * 创建token令牌
     *
     * @param memberId
     * @return
     */
    @Override
    public Token createToken(Integer memberId) {
        String tokenStr = UUID.randomUUID().toString().replace("-", "");
        Token token = new Token(memberId, tokenStr);
        // simpleRedisService.setValueInTime( memberId + "_token",tokenStr, 7*24*3600L);
        simpleRedisService.setValueInTime( memberId + "_token",tokenStr, 30*24*3600L);   //30天免密登录
        return token;
    }

    /**
     * 获取令牌
     *
     * @param tokenStr
     * @return
     */
    @Override
    public Token getToken(String tokenStr) {
        if(StringUtils.isBlank(tokenStr))
            return null;

        String[] params = tokenStr.split("_");
        return new Token(Integer.parseInt(params[0]),params[1]);
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    @Override
    public boolean checkToken(Token token) {
        String tokenStr = simpleRedisService.getByKey(token.getMemberId()+"_token");
        if(!token.getToken().equals(tokenStr)){
            return false;
        }
        //验证成功 延长token存储时间
        // simpleRedisService.expire(token.getMemberId()+"_token",7*24*3600L);
        simpleRedisService.expire(token.getMemberId()+"_token",30*24*3600L);   //30天免密登录
        return true;
    }

    /**
     * 删除token
     *
     * @param memberId
     * @return
     */
    @Override
    public boolean delToken(Integer memberId) {
        simpleRedisService.deleteByKey(memberId+"_token");
        return true;
    }
}
